<?php

namespace App\Controller\Api;

use App\Base\BaseController4Restful;
use App\Entity\UserContact;
use App\Repository\UserContactRepository;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Routing\Annotation\Route;

class ApiUserContactController extends BaseController4Restful
{
    /**
     * @Route("/api/userContacts", name="apiGetUserContacts",methods={"GET","POST"})
     */
    public function apiGetUserContacts(UserContactRepository $repository,Request $request)
    {
        $user = $this->needToBeUser();
        switch ($request->getMethod()) {
            case "POST":
                $data = $this->getRequestData();
                $data["phone"] .="";
                /**@var $UserContact UserContact*/
                $UserContact = $this->createEntity($data,UserContact::class);
                $UserContact->setIsDel(0)->setIsDefault(0)->setUser($user);
                $this->myEm()->persist($UserContact);$this->myEm()->flush();
                return $this->json_out(200,"创建成功", $UserContact);
            default:
                if (!$page = $this->getParamRequired("page")) {$page = 1;}
                $limit = 10;
                $offset = (int)abs($limit * ($page - 1));
                $total = $repository->count([]);
                $this->setMeta($page,$total,$limit);
                $list = $repository->findBy(array("user"=>$user,"isDel"=>0),array("isDefault"=>"DESC","id"=>"DESC"),$limit,$offset);
                return $this->json_out(200,"获取成功", $list);
        }
    }

    /**
     * @Route("/api/userContacts/{id}", name="apiAddUserContacts",methods={"GET","PUT","PATCH","DELETE"})
     */
    public function apiUpdateUserContacts(UserContact $UserContact,Request $request)
    {
        $user = $this->needToBeUser();

        $data = $this->getRequestData();
        switch ($request->getMethod()) {
            case "DELETE":
                if ($UserContact->getUser() != $user) {
                    return $this->json_out(400,"权限不足");
                }
                $this->myEm()->remove($UserContact);$this->myEm()->flush();
                return $this->json_out(200,"已移除");
            case "PATCH":
            case "PUT":
                if ($UserContact->getUser() != $user) {
                    return $this->json_out(400,"权限不足");
                }
                $data["phone"] .="";
                /**@var $UserContact UserContact*/
                $UserContact = $this->updateEntity($data,UserContact::class,$UserContact);
                $this->myEm()->persist($UserContact);$this->myEm()->flush();
                break;
            case "Get":
            default:
        }
        return $this->json_out(200,"获取成功", $UserContact);
    }
}
